﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Janus.Windows.GridEX;

namespace YiLe.UI
{
    public partial class GridEXView 
    {

        protected override void OnDataProviderChanged()
        {
            this.GridEX.DataSource = this.DataSource;
        }

        public override bool UpdateChanges()
        {
            return this.GridEX.UpdateData();
        }

        public override FolderView[] GetDefinedViews()
        {
            //TODO: Load the layout file to include the layouts saved in there 
            //that are not present in the layout
            ArrayList list = new ArrayList();
            AddViews(this.GridEX.Layouts, list);
            FolderView[] views = new FolderView[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                GridEXLayout layout = (GridEXLayout)(list[i]);
                views[i] = new FolderView(layout.Description, ApplicationFolder.ContentViewType.GridView, layout.Key);
            }
            return views;
        }

        private void AddViews(GridEXLayoutCollection layouts, ArrayList list)
        {
            foreach (GridEXLayout layout in layouts)
            {
                if (layout.Tag != "NOSHOW")
                {
                    list.Add(layout);
                }
                AddViews(layout.ChildLayouts, list);
            }
        }

        public override int ItemCount
        {
            get
            {
                return this.GridEX.RecordCount;
            }
        }

        public override bool Printable
        {
            get
            {
                return true;
            }
        }

        public override void PrintPreview(Form ownerForm)
        {
            frmPrintPreview preview = new frmPrintPreview();
            preview.Show(this.printDocument, ownerForm);
        }

        public override void Print()
        {
            try
            {
                this.printDocument.Print();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, YiLeSystemApp.MessageCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GridEX_SelectionChanged(object sender, System.EventArgs e)
        {
            OnCurrentItemChanged(EventArgs.Empty);
        }

        [System.ComponentModel.Browsable(true)]
        public override object CurrentItem
        {
            get
            {
                GridEXRow currentRow = null;
                currentRow = GridEX.GetRow();
                if (currentRow != null && currentRow.RowType == RowType.Record)
                {
                    //return the DataRow object.
                    DataRowView dataRow = currentRow.DataRow as DataRowView;
                    if (dataRow != null)
                    {
                        return dataRow.Row;
                    }
                }
                return null;

            }
        }

        public override bool CanDelete
        {
            get
            {
                if (this.GridEX.AllowDelete == InheritableBoolean.True)
                {
                    //return true only if at least one of the selected items
                    //is a record
                    foreach (GridEXSelectedItem item in GridEX.SelectedItems)
                    {
                        if (item.RowType == RowType.Record)
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
        }

        public override bool CanEdit
        {
            get
            {
                //return true only if at least one of the selected items
                //is a record
                foreach (GridEXSelectedItem item in GridEX.SelectedItems)
                {
                    if (item.RowType == RowType.Record && item.Table == this.GridEX.RootTable)
                    {
                        return true;
                    }
                }
                return false;
            }
        }

        public override void Delete()
        {
            this.GridEX.Delete();
        }

        public override Janus.Windows.UI.CommandBars.UICommandManager ControlCommandManager
        {
            get
            {
                return commandManager;
            }
        }
        public override Janus.Windows.Ribbon.Ribbon RibbonControl
        {
            get
            {
                return this.ribbon1;
            }
        }
        private void commandManager_CommandClick(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
        {
            switch (e.Command.Key)
            {
                case "cmdShowFields":
                    ShowFieldsDialog();
                    break;
                case "cmdSort":
                    ShowSortDialog();
                    break;
                case "cmdGroupBy":
                    ShowGroupByDialog();
                    break;
                case "cmdFormatView":
                    this.ShowFormatViewDialog();
                    break;
                case "cmdAutomaticFormatting":
                    this.ShowFormatConditionsDialog();
                    break;
                case "cmdViewSummary":
                    this.ShowViewSummaryDialog();
                    break;
                case "rcmdGroupByBox":
                    this.OnGroupByBoxCommand();
                    break;
                default:
                    this.cmHeader_CommandClick(cmHeader, e);
                    break;
            }
        }
        public void ShowViewSummaryDialog()
        {
            frmViewSummary frm = new frmViewSummary();
            frm.ShowDialog(this.GridEX, this.ParentForm, this);
            frm.Dispose();
        }


        public void ShowSortDialog()
        {
            frmSort frm = new frmSort();
            frm.ShowDialog(this.GridEX, this.ParentForm);
            frm.Dispose();
        }
        public void ShowFieldsDialog()
        {
            frmShowFields frm = new frmShowFields();
            frm.ShowDialog(this.GridEX, this.ParentForm);
            frm.Dispose();
        }
        public void ShowFormatViewDialog()
        {
            frmFormatView frm = new frmFormatView();
            frm.ShowDialog(this.GridEX, this.ParentForm);
            frm.Dispose();

        }
        public void ShowFormatConditionsDialog()
        {
            frmFormatConditions frm = new frmFormatConditions();
            frm.ShowDialog(this.GridEX, this.ParentForm);
            frm.Dispose();
        }
        public void ShowGroupByDialog()
        {
            frmGroupBy frm = new frmGroupBy();
            frm.ShowDialog(GridEX, this.ParentForm);
            frm.Dispose();
        }
        public void ShowFilterDialog()
        {
            frmFilter frm = new frmFilter();
            frm.ShowDialog(this.GridEX, this.ParentForm);
            frm.Dispose();
        }
        private void GridEX_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (GridEX.HitTest(e.X, e.Y) == GridArea.ColumnHeader)
                {
                    GridEXColumn colClicked = GridEX.ColumnFromPoint(e.X, e.Y);
                    if (colClicked != null)
                    {
                        this.ShowHeaderMenu(colClicked);
                    }
                }
            }
        }
        private GridEXColumn mContextMenuColumn;
        private void ShowHeaderMenu(GridEXColumn column)
        {

            mContextMenuColumn = column;
            //Check SortAscending/SortDescending menus if the column is sorted
            if (mContextMenuColumn.SortOrder == Janus.Windows.GridEX.SortOrder.Ascending)
            {
                this.cmdSortAscending.IsChecked = true;
            }
            else
            {
                this.cmdSortAscending.IsChecked = false;
            }
            if (mContextMenuColumn.SortOrder == Janus.Windows.GridEX.SortOrder.Descending)
            {
                this.cmdSortDescending.IsChecked = true;
            }
            else
            {
                this.cmdSortDescending.IsChecked = false;
            }
            //Change the name of GroupByThisField menu depending on whether the column
            //is grouped or not
            if (mContextMenuColumn.Group == null)
            {
                this.cmdGroupByThisField.Text = "&Group By This Field";
            }
            else
            {
                this.cmdGroupByThisField.Text = "Don't &Group By This Field";
            }
            //check group by box menu if the group by box is visible
            if (this.GridEX.GroupByBoxVisible)
            {
                this.cmdGroupByBox.IsChecked = true;
            }
            else
            {
                this.cmdGroupByBox.IsChecked = false;
            }
            if (mContextMenuColumn.ColumnType == ColumnType.CheckBox)
            {
                this.cmdColumnAlignment.IsEnabled = false;
            }
            else
            {
                this.cmdColumnAlignment.IsEnabled = true;
                this.cmdAlignRight.IsChecked = (mContextMenuColumn.TextAlignment == TextAlignment.Far);
                this.cmdAlignCenter.IsChecked = (mContextMenuColumn.TextAlignment == TextAlignment.Center);
                this.cmdAlignLeft.IsChecked = (mContextMenuColumn.TextAlignment == TextAlignment.Near | mContextMenuColumn.TextAlignment == TextAlignment.Empty);

            }
            if (this.GridEX.View != Janus.Windows.GridEX.View.TableView | this.GridEX.RootTable.CellLayoutMode == CellLayoutMode.UseColumnSets)
            {
                this.cmdFieldChooser.IsEnabled = false;
            }
            else
            {
                this.cmdFieldChooser.IsEnabled = true;
            }
            if (mContextMenuColumn.Table.CellLayoutMode == CellLayoutMode.UseColumnSets)
            {
                this.cmdRemoveThisColumn.IsEnabled = false;
            }
            else
            {
                this.cmdRemoveThisColumn.IsEnabled = true;
            }
            if (GridEX.IsFieldChooserVisible())
            {
                this.commandManager.Commands["cmdFieldChooser"].Checked = Janus.Windows.UI.InheritableBoolean.True;
            }
            else
            {
                this.commandManager.Commands["cmdFieldChooser"].Checked = Janus.Windows.UI.InheritableBoolean.False;
            }
            this.cmHeader.Show(this.GridEX);
            mContextMenuColumn = null;
        }

        private void cmHeader_CommandClick(object sender, Janus.Windows.UI.CommandBars.CommandEventArgs e)
        {
            switch (e.Command.Key)
            {
                case "cmdSortAscending":
                    OnSortAscendingCommand();
                    break;
                case "cmdSortDescending":
                    OnSortDescendingCommand();
                    break;
                case "cmdGroupByThisField":
                    OnGroupByThisFieldCommand();
                    break;
                case "cmdGroupByBox":
                    OnGroupByBoxCommand();
                    break;
                case "cmdRemoveThisColumn":
                    OnRemoveThisColumnCommand();
                    break;
                case "cmdFieldChooser":
                    OnFieldChooserCommand();
                    break;
                case "cmdFilter":
                    OnFilterCommand();
                    break;
                case "cmdBestFit":
                    mContextMenuColumn.AutoSize();
                    break;
                case "cmdCustomizeView":
                    this.ShowViewSummaryDialog();
                    break;
                case "cmdAlignLeft":
                    mContextMenuColumn.TextAlignment = TextAlignment.Near;
                    break;
                case "cmdAlignRight":
                    mContextMenuColumn.TextAlignment = TextAlignment.Far;
                    break;
                case "cmdAlignCenter":
                    mContextMenuColumn.TextAlignment = TextAlignment.Center;
                    break;
                default:
                    break;
            }
        }

        private void OnSortAscendingCommand()
        {
            if (mContextMenuColumn.Group != null)
            {
                mContextMenuColumn.Group.SortOrder = Janus.Windows.GridEX.SortOrder.Ascending;
            }
            else if (mContextMenuColumn.SortKey != null)
            {
                mContextMenuColumn.SortKey.SortOrder = Janus.Windows.GridEX.SortOrder.Ascending;
            }
            else
            {
                mContextMenuColumn.Table.SortKeys.Clear();
                mContextMenuColumn.Table.SortKeys.Add(new GridEXSortKey(mContextMenuColumn, Janus.Windows.GridEX.SortOrder.Ascending));
            }
        }
        private void OnSortDescendingCommand()
        {
            if (mContextMenuColumn.Group != null)
            {
                mContextMenuColumn.Group.SortOrder = Janus.Windows.GridEX.SortOrder.Descending;
            }
            else if (mContextMenuColumn.SortKey != null)
            {
                mContextMenuColumn.SortKey.SortOrder = Janus.Windows.GridEX.SortOrder.Descending;
            }
            else
            {
                mContextMenuColumn.Table.SortKeys.Clear();
                mContextMenuColumn.Table.SortKeys.Add(new GridEXSortKey(mContextMenuColumn, Janus.Windows.GridEX.SortOrder.Descending));
            }
        }
        private void OnGroupByThisFieldCommand()
        {
            if (mContextMenuColumn.Group == null)
            {
                mContextMenuColumn.Table.Groups.Add(new GridEXGroup(mContextMenuColumn));
            }
            else
            {
                mContextMenuColumn.Table.Groups.Remove(mContextMenuColumn.Group);
            }
        }
        private void OnGroupByBoxCommand()
        {
            GridEX.GroupByBoxVisible = !GridEX.GroupByBoxVisible;
        }
        private void OnRemoveThisColumnCommand()
        {
            mContextMenuColumn.Visible = false;

        }
        private frmFieldChooser fieldChoser;
        private void OnFieldChooserCommand()
        {
            if (fieldChoser == null || fieldChoser.IsDisposed)
            {
                fieldChoser = new frmFieldChooser();
                fieldChoser.Show(this.GridEX, this.FindForm());
            }
            else
            {
                fieldChoser.Close();
                fieldChoser.Dispose();
                fieldChoser = null;
            }
        }
        private bool filterEditorVisible = false;
        public bool FilterEditorVisible
        {
            get
            {
                return this.filterEditorVisible;
            }
            set
            {
                this.filterEditorVisible = value;
                this.FilterEditor1.Visible = this.filterEditorVisible;
                this.rcmdFilterEditor.Checked = this.filterEditorVisible;
                this.cmdFilter.IsChecked = this.filterEditorVisible;
                this.cmdFilter2.IsChecked = this.filterEditorVisible;
            }
        }
        private void OnFilterCommand()
        {
            this.FilterEditorVisible = !this.FilterEditorVisible;
        }

        private void GridEX_DoubleClick(object sender, System.EventArgs e)
        {
            //get the area where the user is clicking:
            GridArea clickArea = GridEX.HitTest();
            switch (clickArea)
            {
                case GridArea.GroupByBox:
                case GridArea.GroupByBoxInfoText:
                    this.ShowGroupByDialog();
                    break;
                case GridArea.Cell:
                case GridArea.PreviewRow:
                case GridArea.CardCaption:
                    this.Edit();

                    break;
            }
        }


        private void UpdateLayout()
        {
            if (this.GridEX.CurrentLayout != null)
            {
                //first clear all valuelist to avoid saving them in the layout
                //file. ValueList in this app, are filled when the control is loaded
                //so there is no need to preserve them
                foreach (GridEXTable t in GridEX.Tables)
                {
                    foreach (GridEXColumn c in t.Columns)
                    {
                        if (c.HasValueList)
                        {
                            c.ValueList.Clear();
                        }
                    }
                }
                this.GridEX.CurrentLayout.Update();
            }
        }

        protected override void OnFolderViewChanged()
        {
            UpdateLayout();
        }

        public override void SaveSettings()
        {
            UpdateLayout();

            //TODO: ADD SAVE SETTINGS

            /*ConfigDataSet.ContentViewSettingsRow viewRow = YiLeSystemApp.ConfigDataSet.ContentViewSettings.FindByViewName(this.GetType().FullName);

            if (viewRow == null)
            {
                viewRow = YiLeSystemApp.ConfigDataSet.ContentViewSettings.AddContentViewSettingsRow(this.GetType().FullName, "");
            }
            viewRow.BeginEdit();
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            this.GridEX.SaveLayoutFile(stream);
            viewRow.Layout = System.Convert.ToBase64String(stream.ToArray());
            stream.Close();
            viewRow.EndEdit();*/
        }

        public override void LoadSettings()
        {
            //Load saved layout if the application is reading layouts and 
            //if it exist in the config dataset
            //TODO: ADD LOADING SETTINGS
            /*if (YiLeSystemApp.ReadSettingsFromDS)
            {
                ConfigDataSet.ContentViewSettingsRow viewRow = YiLeSystemApp.ConfigDataSet.ContentViewSettings.FindByViewName(this.GetType().FullName);

                if (viewRow != null)
                {
                    if (!viewRow.IsLayoutNull() && viewRow.Layout.Length > 0)
                    {
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Convert.FromBase64String(viewRow.Layout));
                        this.GridEX.LoadLayoutFile(stream);
                        stream.Close();
                    }
                }
            }*/

        }
        public override string StatusBarInfo
        {
            get
            {
                return this.GridEX.RecordCount + " Items";
            }
        }

        private void GridEX_RowCountChanged(object sender, System.EventArgs e)
        {
            if (YiLeSystemApp.MainForm != null)
            {

                //TODO:YiLeSystemApp.MainForm.ResetStatusBarInfo();
                //YiLeSystemApp.MainForm.ResetStatusBarInfo();
            }
        }
        protected void EnableCommands()
        {
            if (this.GridEX.View == Janus.Windows.GridEX.View.TableView)
            {
                this.cmdGroupByBox.IsChecked = this.GridEX.GroupByBoxVisible;
                this.cmdGroupByBox.IsEnabled = true;
                this.rcmdGroupByBox.Checked = true;
                this.rcmdGroupByBox.Enabled = true;
            }
            else
            {
                this.cmdGroupByBox.IsEnabled = false;
                this.cmdGroupByBox.IsChecked = false;
                this.rcmdGroupByBox.Checked = false;
                this.rcmdGroupByBox.Enabled = false;
            }
            /*if (this.GridEX.View != Janus.Windows.GridEX.View.TableView | this.GridEX.RootTable.CellLayoutMode == CellLayoutMode.UseColumnSets)
            {
                this.cmdFieldChooser.IsEnabled = false;
            }
            else
            {
                this.cmdFieldChooser.IsEnabled = true;
            }*/
        }

        public GridEXView()
        {

            // This call is required by the Windows Form Designer.
            InitializeComponent();

            // Add any initialization after the InitializeComponent() call.
            this.FilterEditor1.BackColor = this.GridEX.GroupByBoxFormatStyle.BackColor;

        }


        private void GridEXView_Load(object sender, System.EventArgs e)
        {
            this.FilterEditor1.VisualStyleManager.ColorSchemeChanged += new Janus.Windows.Common.ColorSchemeChangedEventHandler(this.VisualStyleManager_ColorSchemeChanged);
            this.FilterEditor1.BackColor = this.GridEX.GroupByBoxFormatStyle.BackColor;

        }

        private void GridEXView_SystemColorsChanged(object sender, System.EventArgs e)
        {
            this.FilterEditor1.BackColor = this.GridEX.GroupByBoxFormatStyle.BackColor;
        }

        private void VisualStyleManager_ColorSchemeChanged(object sender, Janus.Windows.Common.ColorSchemeChangedEventArgs e)
        {
            this.FilterEditor1.BackColor = this.GridEX.GroupByBoxFormatStyle.BackColor;

        }

        private void ribbon1_CommandClick(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            switch (e.Command.Key)
            {
                case "rcmdFieldChooser":
                    this.OnFieldChooserCommand();
                    break;
                case "rcmdFilterEditor":
                    this.OnFilterCommand();
                    break;
                case "rcmdGroupByBox":
                    this.OnGroupByBoxCommand();
                    break;
                case "rcmdShowFields":
                    this.ShowFieldsDialog();
                    break;
                case "rcmdGroupBy":
                    this.ShowGroupByDialog();
                    break;
                case "rcmdSort":
                    this.ShowSortDialog();
                    break;
                case "rcmdFormatView":
                    this.ShowFormatViewDialog();
                    break;
                case "rcmdFormatConditions":
                    this.ShowFormatConditionsDialog();
                    break;
                case "rcmdViewSummary":
                    this.ShowViewSummaryDialog();
                    break;
            }
        }
    }
}
